import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:test_flutter/cache/UserDataCache.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/response/user_model.dart';
import 'package:test_flutter/model/scoped_model/main_model.dart';
import 'package:test_flutter/pages/Base/LBaseState.dart';
import 'package:test_flutter/pages/ForgetPWPage.dart';
import 'package:test_flutter/pages/HomePage.dart';
import 'package:test_flutter/pages/RegisterPage.dart';
import 'package:test_flutter/utils/ColorsUtil.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:test_flutter/utils/overLay_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import 'dart:async';

class LoginPage extends StatefulWidget {
  final String pageText; //定义一个常量，用于保存跳转进来获取到的参数
  LoginPage(this.pageText); //构造函数，获取参数
  @override
  _LoginPage createState() => new _LoginPage(pageText);
}

class _LoginPage extends LBaseState<LoginPage> {
  final String pageText; //定义一个常量，用于保存跳转进来获取到的参数
  _LoginPage(this.pageText); //构造函数，获取参数

  //bool isHideLoading = true;
  bool canClick = true;

  var _userNameController = new TextEditingController();
  var _userPassController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    CustomLocalizations.init(context);
    return MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.green,
        brightness: Brightness.light,
      ),
      home: new Scaffold(
        resizeToAvoidBottomPadding: true, //输入框抵住键盘
        body: new SingleChildScrollView(
          child: new Stack(
            children: <Widget>[
              new Container(
                width: Fit.scaleX(1080),
                height: Fit.scaleY(1920),
                color: Color(0xFFF0F0F0),
              ),
              new Positioned(
                  child: new Container(
                width: Fit.scaleX(1080),
                height: Fit.scaleY(980),
                decoration: BoxDecoration(
                    gradient: const LinearGradient(colors: [
                  Color(0xFF00E579),
                  Color(0xFF00E585),
                  Color(0xFF00E792),
                  Color(0xFF00E8A4),
                  Color(0xFF00ECBA)
                ])),
              )),
              new Positioned(
                  right: Fit.scaleX(50),
                  left: Fit.scaleX(50),
                  top: Fit.scaleY(600),
                  child: Material(
                    elevation: 14.0,
                    borderRadius: BorderRadius.circular(12.0),
                    shadowColor: Color(0x802196F3),
                    child: new Container(
                      height: Fit.scaleX(700),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(Fit.scaleX(30)),
                        color: Color(0xFFFFFFFF),
                      ),
                      child: new Column(
                        children: <Widget>[
                          new Padding(
                            padding: new EdgeInsets.only(
                                left: Fit.scaleX(50),
                                top: Fit.scaleY(80),
                                right: Fit.scaleX(50)),
                            child: new TextField(
                              style: new TextStyle(
                                  fontSize: Fit.scaleTextSize(40),
                                  color: Colors.black26),
                              controller: _userNameController,
                              decoration: new InputDecoration(
                                  hintText: CustomLocalizations.instance
                                      .getString(StringIds.pleaseEnterUserName),
                                  icon: Icon(
                                      IconData(0xe616,
                                          fontFamily: "wxcIconFont"),
                                      size: 16.0)),
                              obscureText: false,
                            ),
                          ),
                          new Padding(
                            padding: new EdgeInsets.only(
                                left: Fit.scaleX(50),
                                top: Fit.scaleY(80),
                                right: Fit.scaleX(50)),
                            child: new TextField(
                              style: new TextStyle(
                                  fontSize: Fit.scaleTextSize(40),
                                  color: Colors.black26),
                              controller: _userPassController,
                              decoration: new InputDecoration(
                                  hintText: CustomLocalizations.instance
                                      .getString(StringIds.pleaseEnterPassWord),
                                  icon: Icon(
                                      IconData(0xe61b,
                                          fontFamily: "wxcIconFont"),
                                      size: 16.0)),
                              obscureText: true,
                            ),
                          )
                        ],
                      ),
                    ),
                  )),
              new Positioned(
                  right: Fit.scaleX(100),
                  left: Fit.scaleX(100),
                  top: Fit.scaleY(1400),
                  child: new FlatButton(
                    color: Color(0xFF00E8A4),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(Fit.scaleX(90)),
                        topLeft: Radius.circular(Fit.scaleX(90)),
                        bottomRight: Radius.circular(Fit.scaleX(90)),
                        bottomLeft: Radius.circular(Fit.scaleX(90)),
                      ),
                    ),
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(Fit.scaleX(20),
                          Fit.scaleX(60), Fit.scaleX(20), Fit.scaleX(60)),
                      child: new Text(
                        CustomLocalizations.instance
                            .getString(StringIds.login),
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: Fit.scaleTextSize(48)),
                      ),
                    ),
                    onPressed: canClick
                        ? () {
                            /*Navigator.of(context).pushAndRemoveUntil(
                          new MaterialPageRoute(builder: (context) => new HomePage('主页')),
                              (Route<dynamic> rout) => false);*/
                            login();
                          }
                        : () {},
                  )),
              new Positioned(
                  left: Fit.scaleX(500),
                  top: Fit.scaleY(1700),
                  child: new GestureDetector(
                    onTap: () {
                      Navigator.push<Object>(context, new MaterialPageRoute(
                          builder: (BuildContext context) {
                        return new RegisterPage();
                      }));
                    },
                    child: new Text(
                      CustomLocalizations.instance
                          .getString(StringIds.register),
                      style: TextStyle(
                          color: ColorsUtil.Green,
                          fontSize: Fit.scaleTextSize(50)),
                    ),
                  )),
              new Positioned(
                  right: Fit.scaleX(280),
                  top: Fit.scaleY(250),
                  child: new Text('',
                      style: TextStyle(
                        color: Color(0xFFFFFFFF),
                        fontSize: Fit.scaleTextSize(80),
                        fontWeight: FontWeight.bold,
                      ))),
              new Positioned(
                right: Fit.scaleX(180),
                top: Fit.scaleY(1050),
                child: new GestureDetector(
                    onTap: () {
                      //ToastUtil.showToast('忘记密码');
                      // util.callTelephone('13957364530');
                      Navigator.push<Object>(context, new MaterialPageRoute(
                          builder: (BuildContext context) {
                        return new ForgetPWPage();
                      }));
                    },
                    child: new Text(
                      CustomLocalizations.instance
                          .getString(StringIds.forgetPassWord),
                      style: TextStyle(color: ColorsUtil.Green),
                    )),
              ),
              /*new Positioned(
                  top: Fit.scaleY(800),
                  left: Fit.scaleX(490),
                  child: Container(
                    width: Fit.scaleX(100),
                    height: Fit.scaleX(100),
                    child: Offstage(
                        offstage: isHideLoading,
                        child: CircularProgressIndicator()
                    ),
                  )),*/
            ],
          ),
        ),
      ),
    );
  }

  Future<Null> _launchInBrowser(String url) async {
    if (await canLaunch(url)) {
      await launch(url, forceSafariVC: false, forceWebView: false);
    } else {
      throw 'Could not launch $url';
    }
  }

  //登录方法

  void login() async {
    if (_userNameController.text.length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance
          .getString(StringIds.pleaseEnterUserName));
      return;
    }

    if (_userPassController.text.length == 0) {
      ToastUtil.showToast(CustomLocalizations.instance
          .getString(StringIds.pleaseEnterPassWord));
      return;
    }

    if (_userPassController.text.length < 6) {
      ToastUtil.showToast(CustomLocalizations.instance
          .getString(StringIds.AtLeast6Bytes));
      return;
    }

    OverlayUtil.showOverlay(context);

    setState(() {
      canClick = false;
      //isHideLoading = false;
    });

    Map<String, String> requestMap = new Map();
    requestMap['MobileNo'] = _userNameController.text;
    requestMap['Password'] = _userPassController.text;

    DioUtil.getInstance(context).post(
        Api.login,
        (response) {
          if (response.data['code'] == 1) {
            savaData(context, response);
          } else {
            ToastUtil.showToast(response.data['msg']);
          }

          setState(() {
            canClick = true;
            //isHideLoading = true;

          });

          OverlayUtil.hideOverlay();
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error==========:" + errorMsg);
          ToastUtil.showToast(errorMsg);
          setState(() {
            canClick = true;
            //isHideLoading = true;

          });
          OverlayUtil.hideOverlay();
        });
  }

  //用户数据和token  持久化
  savaData(BuildContext context, Response response) async {
    UsersModel user = UsersModel.fromJson(response.data['data']['user']);
    await UserDataCache.getInstance().setUser(context, user); //保存用户数据
    await UserDataCache.getInstance()
        .setToken(response.data['data']['token']['AccessToken']); //保存token
    Navigator.of(context).pushAndRemoveUntil(
        new MaterialPageRoute(builder: (context) => new HomePage('主页')),
        (Route<dynamic> rout) => false);
  }
}
